import json
import requests
from odoo import http
from odoo.http import request
import logging

_logger = logging.getLogger(__name__)


# Odoo 线上服务器信息
# odoo_url = 'http://10.150.200.1:8069'   # 本地测试地址
# db = 'WTT_odoo17_text'                  # 本地测试数据库名称
# username = 'WTT_administrator_text'     # odoo 管理员用户
# password = 'WTT@odoo!!'                  # 管理员密码

# odoo_url = 'http://127.0.0.1:8090'   # 本地测试地址
# db = 'odoo17e'                      # 本地测试数据库名称
# username = 'admin'                   # odoo 管理员用户
# password = '123456'                  # 管理员密码


class GetToken(http.Controller):
    def odoo_login(self, odoo_url, db, username, password):
        """登录到 Odoo 并返回用户 ID 和会话头"""

        login_url = f'{odoo_url}/web/session/authenticate'
        payload = {
            'jsonrpc': '2.0',
            'params': {
                'db': db,
                'login': username,
                'password': password,
            }
        }
        response = requests.post(login_url, json=payload)
        if response.status_code == 200:
            response_body = response.json()
            uid = response_body['result'].get('uid')
            headers = response.headers.get('Set-Cookie')
            return {"headers": headers, "uid": uid}
        else:
            return {"error": "Login failed!"}

    @http.route("/api/work_center/get_token", auth='public', type='http', methods=['GET'], csrf=False)
    def get_partners_info(self, **kwargs):
        """获取合作伙伴信息和访问令牌"""
        config = request.env['ir.config_parameter'].sudo()
        odoo_url = config.get_param('odoo.url')
        db = config.get_param('odoo.db')
        username = config.get_param('odoo.username')
        password = config.get_param('odoo.password')
        session_info = self.odoo_login(odoo_url, db, username, password)
        if 'error' in session_info:
            return http.Response(json.dumps(session_info))

        headers_ = session_info.get('headers')
        uid = session_info.get('uid')
        headers = {
            'Content-Type': 'application/json',
            'X-Openerp-Session-Id': headers_,
        }
        search_url = f'{odoo_url}/jsonrpc'
        search_payload = {
            'jsonrpc': '2.0',
            'method': 'call',
            'args': [
                db,
                uid,
                password,
                'res.partner',  # 访问的模型
                'search_read',  # 搜索
                [],  # 搜索条件，这里为空表示获取所有记录
                {'fields': ['id', 'name', 'email'], 'limit': 10}  # 指定需要返回的字段和限制记录数
            ],
            'id': 1,
        }
        response = requests.post(search_url, headers=headers, json=search_payload)
        if response.status_code == 200:
            data = response.json()
            _logger.info('/work_center/get_token:data %s' % data)
            result = {
                'Cookie': headers_,
                'uid': uid,
                'partners': data.get('result', [])
            }
            return http.Response(json.dumps(result), content_type='application/json')
        else:
            return http.Response(json.dumps({'error': 'Failed to fetch partners'}), content_type='application/json',
                                 status=500)

    @http.route('/api/auth', type='http', auth='public', methods=["GET", "OPTIONS"], csrf=False, cors='*')
    def api_authenticate(self, **post):
        config = request.env['ir.config_parameter'].sudo()
        odoo_url = config.get_param('odoo.url')
        db = config.get_param('odoo.db')
        username = config.get_param('odoo.username')
        password = config.get_param('odoo.password')
        AUTH_URL = f"{odoo_url}/web/session/authenticate/"
        headers = {'Content-type': 'application/json'}
        data = {
            "jsonrpc": "2.0",
            "params": {
                "login": username,
                "password": password,
                "db": db
            }
        }
        res = requests.post(
            AUTH_URL,
            data=json.dumps(data),
            headers=headers
        )
        try:
            data = res.json()
            _logger.info('/api/auth:data %s' % data)
            session_id = res.cookies["session_id"]
        except Exception as e:
            return http.Response(json.dumps({'code': 202, 'message': '账号/密码/数据库错误！'}),
                                 content_type='application/json')
        return http.Response(json.dumps({'code': 200, 'data': {'session_id': session_id}}),
                             content_type='application/json', )
